package be.dataflow.xtime;

import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import be.dataflow.xtime.DFHttpClient.ApiException;

/**
 * Main application activity
 * 
 */
public class XtimeActivity extends Activity implements View.OnClickListener {

	public static final String baseurl = "http://trace.copywaste.org/";
	public static final int PERIOD = 300000; // 5 minutes

	/**
	 * unique identifiers for context menu items
	 */
	private static final int ACTIVITY_PREFERENCES = 1;
	private static final int MENU_DIALOG = 2;
	private static final int MENU_TOAST = 3;
	private static final int MENU_NOTIFICATION = 4;
	private static final int DIALOG_FROM_LIST = 5;
	private static final int HELLO_ID = 6;

	/**
	 * reference to preferences
	 */
	private static SharedPreferences prefs;

	/**
	 * property that can be set by user in preferences activity
	 */
	private boolean showLifeCycleMessage = true;

	/**
	 * reference to the list
	 */
	private ListView list;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// link with an xml layout resource
		setContentView(R.layout.main);

		// Setting up the Alarm Manager
		AlarmManager mgr = (AlarmManager) this
				.getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent(this, OnAlarmReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

		mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
				SystemClock.elapsedRealtime() + 60000, PERIOD, pi);

		// TODO get reference to listview object from layout xml file
		// list = ... ;

		// TODO update adapter to load with data from R.array.listValues as
		// values and android.R.layout.simple_list_item_1 for layout
		// list.setAdapter( ... );

		// TODO register listener on listview for a single click showing Toast
		// message with selected item
		// list.set ... ;

		// TODO register listener to listview for context menu
		// ...
	}

	@Override
	protected void onStart() {
		super.onStart();

		// example of getting preferences in application for use
		prefs = PreferenceManager.getDefaultSharedPreferences(this);

		// TODO get the checkboxPref property, use false as default value
		// showLifeCycleMessage = ... ;

		// for demo only show lifecycle of app if this property is set
		if (showLifeCycleMessage)
			showToast("Lifecycle: onStart");
	}

	@Override
	protected void onStop() {
		super.onStop();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onStop");

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onDestroy");

	}

	@Override
	protected void onPause() {
		super.onPause();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onPause");

	}

	@Override
	protected void onRestart() {
		super.onRestart();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onRestart");

	}

	@Override
	protected void onResume() {
		super.onResume();

		// for demo only show lifecycle of app
		if (showLifeCycleMessage)
			showToast("Lifecycle: onResume");

	}

	/**
	 * We're catching button clicks here
	 */
	public void onClick(View v) {
		Button b = (Button) v;
		final String message = b.getText().toString();

		switch (v.getId()) {
		case R.id.dinnertime_btn:
		case R.id.bedtime_btn:
		case R.id.sexytime_btn:
			// Send a message in a background thread
			new Thread(new Runnable() {
				public void run() {
					try {
						// TODO create JSON request with message and nickname
						// ...
						// TODO post to baseurl
						// ...
					} catch (JSONException e1) {
						e1.printStackTrace();
					} catch (ApiException e) {
						e.printStackTrace();
					}
				}
			}).start();

			break;
		default:
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// TODO add item to options menu for preferences, use
		// R.string.menu_preferences as label
		// ... ;
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		boolean bla = super.onMenuItemSelected(featureId, item);

		switch (item.getItemId()) {
		// link the preference option to the preference activity
		case ACTIVITY_PREFERENCES:
			// TODO start the preferences activity here
			// ... ;
			return (true);
		}

		return bla;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// add the menu items
		menu.add(0, MENU_DIALOG, 1, R.string.show_dialog);
		menu.add(0, MENU_TOAST, 1, R.string.show_toast);
		menu.add(0, MENU_NOTIFICATION, 1, R.string.show_notification);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
		// .getMenuInfo();
		switch (item.getItemId()) {
		case MENU_DIALOG:
			showDialog(DIALOG_FROM_LIST);
			return true;
		case MENU_TOAST:
			showToast("Toasted!");
			return true;
		case MENU_NOTIFICATION:
			showNotification();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_FROM_LIST:
			// Get reference to dialog builder here
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			// TODO create a dialog with a title, message and yes/no options
			// ...
			// return the created dialog
			return builder.create();
		default:
			return super.onCreateDialog(id);

		}
	}

	/**
	 * show a single notification message
	 */
	private void showNotification() {
		// get reference to the notification manager
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = null;
		// TODO create a notification with an icon, text and time to show
		// ...
		// TODO create an intent to attach, use the browser opening google.be
		// for instance
		// ...
		// notify
		mNotificationManager.notify(HELLO_ID, notification);
	}

	/**
	 * show a toast message using the given text
	 * 
	 * @param text
	 *            to show within toast
	 */
	private void showToast(String text) {
		// TODO create a toast message here with the given text
		// ...
	}

}